# -*- coding: utf-8 -*-
import random
import logging
import time
from datetime import timedelta

from common.campaign.db import moist as MoistCampaignDb
from common.utils.tz import local_now, local_to_utc


_LOGGER = logging.getLogger('campaign')

RECHARGE_PRICE = 20
AWARD_PRICE = 100


AWARD_LIST = [{
        'delay_days': 0,
        'coupon_tid': 5,
        'count': 1
    },{
        'delay_days': 1,
        'coupon_tid': 5,
        'count': 2
    },{
        'delay_days': 2,
        'coupon_tid': 5,
        'count': 3
    },{
        'delay_days': 3,
        'coupon_tid': 5,
        'count': 4
    },{
        'delay_days': 4,
        'coupon_tid': 6,
        'count':4 
    },{
        'delay_days': 5,
        'coupon_tid': 6,
        'count': 4
    },{
        'delay_days': 6,
        'coupon_tid': 6,
        'count': 4
    }
]


def award_coupons():
    coupons = []
    local_today = local_now().replace(hour=0, minute=0, second=0)
    for award_conf in AWARD_LIST:
        start_date = local_today + timedelta(award_conf['delay_days'])
        start_ts = int(time.mktime(local_to_utc(start_date).timetuple()))
        for _ in range(award_conf['count']):
            coupons.append({
                'tid': award_conf['coupon_tid'],
                'start_ts': start_ts
            })
    return coupons


def add_new_recharge(user_id, price):
    try:
        if price >= RECHARGE_PRICE:
            _LOGGER.info('moist campaign add new recharge %s for user %s', price, user_id)
            coupons = award_coupons()
            check_in = MoistCampaignDb.check_in(user_id, price, AWARD_PRICE, coupons)
    except Exception as e:
        _LOGGER.exception('moist_campaign add recharge exception:%s', e)


def get_campaign_status(user_id):
    status = MoistCampaignDb.get_status(user_id)
    return 1 if status else 0
